/**
  ******************************************************************************
  * @file    drv_vuart.c/drv_vuart.h
  * @author  杜碧路
  * @version v1.0
  * @date    2021-11-01
  * @brief
  ******************************************************************************
  * @attention
  * 	版本号  日期        作者       说明
  *		v1.0    2021-11-01 杜碧路      
  *
  * copyright (c), 2016-2019, 稳恩佳力佳（北京）石油化工设备有限公司
  ******************************************************************************
  */
#include "board.h"

#include <rtdevice.h>
#include <rtthread.h>
#include "SEGGER_RTT.h"

rt_err_t drv_uart_configure(struct rt_serial_device *serial, struct serial_configure *cfg)
{
    return (RT_EOK);
}
rt_err_t drv_uart_control(struct rt_serial_device *serial, int cmd, void *arg)
{
    return (RT_EOK);
}
int drv_uart_putc(struct rt_serial_device *serial, char c)
{
    return SEGGER_RTT_PutChar(0, c);
}
int drv_uart_getc(struct rt_serial_device *serial)
{
    return SEGGER_RTT_GetKey();
}

rt_size_t drv_uart_dma_transmit(struct rt_serial_device *serial,
                      rt_uint8_t *buf,
                      rt_size_t size,
                      int direction)
{

    return (0);
}

static struct rt_serial_device serialv = {.config =  RT_SERIAL_CONFIG_DEFAULT,};
// 注册一个虚拟串口, 用来连接设备
const struct rt_uart_ops _uart_opss = {
    drv_uart_configure,
    drv_uart_control,
    drv_uart_putc,
    drv_uart_getc,
    drv_uart_dma_transmit,
};

static void segger_rtt_check(void)
{
    uint32_t count = SEGGER_RTT_HasData(0);
    for (uint16_t index = 0 ; index < count; index ++)
    {
        rt_hw_serial_isr(&serialv, RT_SERIAL_EVENT_RX_IND);
    }
}

int virtul_uart_init(void)
{
    struct rt_serial_device *serial = &serialv;
    serial->ops = &_uart_opss;

    SEGGER_RTT_Init();

    rt_thread_idle_sethook(segger_rtt_check);

    SEGGER_RTT_SetTerminal(0);
    SEGGER_RTT_ConfigUpBuffer(0, "RTTUP", NULL, 0, SEGGER_RTT_MODE_NO_BLOCK_SKIP);
    SEGGER_RTT_ConfigDownBuffer(0, "RTTDOWN", NULL, 0, SEGGER_RTT_MODE_NO_BLOCK_SKIP);

    rt_hw_serial_register(serial, "vuart1", RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX, RT_NULL);
    return 0;
}

INIT_BOARD_EXPORT(virtul_uart_init);

/*****************************稳恩佳力佳（北京）石油化工设备有限公司(end of file) *********************************/

